package com.sk.weichat.ui.groupchat;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.Reporter;
import com.sk.weichat.adapter.GroupMembersHeadAdapter;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.bean.RoomMember;
import com.sk.weichat.bean.message.MucRoomMember;
import com.sk.weichat.db.dao.ChatMessageDao;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.db.dao.RoomMemberDao;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.sortlist.BaseSortModel;
import com.sk.weichat.sortlist.SideBar;
import com.sk.weichat.sortlist.SortHelper;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.base.CoreManager;
import com.sk.weichat.ui.dialog.DeleteMemberDialog;
import com.sk.weichat.ui.me.PersonalCenterActivity;
import com.sk.weichat.ui.message.multi.EventGroupStatus;
import com.sk.weichat.ui.message.multi.RoomInfoActivity;
import com.sk.weichat.util.AsyncUtils;
import com.sk.weichat.util.ListUtil;
import com.sk.weichat.util.SearchUtils;
import com.sk.weichat.util.SearchUtils.onItemClickOListener;
import com.sk.weichat.util.TimeUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.view.BannedDialog;
import com.sk.weichat.view.SelectionFrame;
import com.sk.weichat.xmpp.ListenerManager;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import okhttp3.Call;

import static com.sk.weichat.ui.groupchat.RoomChangeContentActivity.CHANGE_RESULT;
import static com.sk.weichat.ui.groupchat.RoomChangeContentActivity.DESCRIBE;
import static com.sk.weichat.ui.groupchat.RoomChangeContentActivity.REMARKNAME;
import static com.sk.weichat.ui.groupchat.RoomChangeContentActivity.USERNAME;

/**
 * 群成员列表
 */
public class GroupMembersListActivity extends BaseActivity implements View.OnClickListener {

    private LinearLayout ll_main;
    private RelativeLayout layout_search;
    private RelativeLayout rt_title;

    private SmartRefreshLayout refresh_layout;
    private RecyclerView pull_refresh_list;
    private RecyclerView recy_head;
    private SideBar mSideBar;
    private TextView mTextDialog;

    private List<BaseSortModel<RoomMember>> mSortRoomMember = new ArrayList<>();
    private List<BaseSortModel<RoomMember>> mSortHeadRoomMember = new ArrayList<>();
    private List<BaseSortModel<RoomMember>> sortedList;

    private Map<String, String> mRemarksMap = new HashMap<>();

    private String mRoomId = "";
    private boolean isLoadByService;
    private boolean isBanned;
    private boolean isDelete;
    private boolean isSetRemark;
    private RoomMember mRoomMember;
    private View headView;
    private String mRoomJid = "";

    private GroupMerbersAdapter mAdapter;
    private GroupMembersHeadAdapter membersHeadAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_members_list);

        mRoomId = getIntent().getStringExtra("roomId");
        mRoomJid = getIntent().getStringExtra("roomJid");
//        Log.e("lzs", "GroupMembersListActivity roomId:" + mRoomId);
//        Log.e("lzs", "GroupMembersListActivity roomJid:" + mRoomJid);
        isLoadByService = getIntent().getBooleanExtra("isLoadByService", false);
        isBanned = getIntent().getBooleanExtra("isBanned", false);
        isDelete = getIntent().getBooleanExtra("isDelete", false);
        isSetRemark = getIntent().getBooleanExtra("isSetRemark", false);
        initActionBar();
        initView();
        loadData();
//        if (isLoadByService) {
//            loadDataByService(false);
//        }
    }

    private void initActionBar() {
        getSupportActionBar().hide();
        findViewById(R.id.iv_title_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        TextView tvTitle = findViewById(R.id.tv_title_center);
        if (isSetRemark) {
            tvTitle.setText("对群成员备注");
        } else if (isBanned) {
            tvTitle.setText("禁言");
        } else {
            tvTitle.setText(R.string.group_member);
        }
    }

    private void initView() {
        ll_main = findViewById(R.id.ll_main);
        rt_title = findViewById(R.id.rt_title);
        layout_search = findViewById(R.id.layout_search);
        layout_search.setOnClickListener(this);
        refresh_layout = findViewById(R.id.refresh_layout);
        pull_refresh_list = findViewById(R.id.pull_refresh_list);

        refresh_layout.setDragRate(0.4f);//刷新拉动阻尼效果，数值越小，拉动距离越大
        refresh_layout.setEnableOverScrollBounce(false);//禁止越界回弹
        refresh_layout.setEnableLoadMore(false);
        refresh_layout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refresh_layout.finishRefresh();
            }
        });
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        pull_refresh_list.setLayoutManager(manager);
        mAdapter = new GroupMerbersAdapter(mSortRoomMember);
        //添加头部
        headView = LayoutInflater.from(this).inflate(R.layout.layout_recy, pull_refresh_list, false);
        if (!isBanned) {//如果不是禁言  就添加头部显示群主和管理员
            mAdapter.addHeaderView(headView);
        }
        TextView tv_title = headView.findViewById(R.id.tv_title);
        tv_title.setVisibility(View.VISIBLE);
        recy_head = headView.findViewById(R.id.recy_had_add);
        membersHeadAdapter = new GroupMembersHeadAdapter(mSortHeadRoomMember);
        recy_head.setLayoutManager(new LinearLayoutManager(this));
        recy_head.setNestedScrollingEnabled(true);
        membersHeadAdapter.setHasStableIds(true);
        recy_head.setAdapter(membersHeadAdapter);
        membersHeadAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

                RoomMember roomMember = mSortHeadRoomMember.get(position).getBean();
                onItemClick(roomMember, position);
            }
        });

        mAdapter.setHasStableIds(true);
        pull_refresh_list.setAdapter(mAdapter);
        //禁止RecyclerView的默认动画
        ((SimpleItemAnimator) pull_refresh_list.getItemAnimator()).setSupportsChangeAnimations(false);
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                RoomMember roomMember = mSortRoomMember.get(position).getBean();
                onItemClick(roomMember, position);
            }
        });
        mSideBar = findViewById(R.id.sidebar);
        mTextDialog = findViewById(R.id.text_dialog);
        mSideBar.setTextView(mTextDialog);
        mSideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                // 该字母首次出现的位置
                int position = ListUtil.getSortRoomMembersPositionForSection(mSortRoomMember, s.charAt(0));
                if (position != -1) {
                    manager.scrollToPositionWithOffset(position + 1, 0);
                    showTextDialog(s);
                }
            }
        });


    }

    private void loadData() {
        if (!DialogHelper.isShowing()) {
            DialogHelper.showDefaulteMessageProgressDialog(this);
        }
        AsyncUtils.doAsync(this, e -> {
            Reporter.post("加载数据失败，", e);
            AsyncUtils.runOnUiThread(this, ctx -> {
                DialogHelper.dismissProgressDialog();
                ToastUtil.showToast(ctx, R.string.data_exception);
            });
        }, c -> {
            List<RoomMember> data = RoomMemberDao.getInstance().getRoomMember(mRoomId);
            Map<String, Integer> existMap = new HashMap<>();
            sortedList = SortHelper.toSortedModelList(data, existMap, RoomMember::getShowName);
            c.uiThread(r -> {
                DialogHelper.dismissProgressDialog();
                if (mSortRoomMember != null) {
                    mSortRoomMember.clear();
                }
                mSideBar.setExistMap(existMap);
                if (!ListUtil.isListEmpty(sortedList)) {
                    mSideBar.searchByFirstStr(sortedList.get(0).getFirstLetter());
                }
                for (int i = 0; i < sortedList.size(); i++) {
                    if (sortedList.get(i).getBean().getRole() == 1 || sortedList.get(i).getBean().getRole() == 2) {
                        if (sortedList.get(i).getBean().getRole() == 1) {
                            mSortHeadRoomMember.add(0, sortedList.get(i));
                        } else {
                            mSortHeadRoomMember.add(sortedList.get(i));
                        }
                    } else {
                        mSortRoomMember.add(sortedList.get(i));
                    }
                }
                if (mSortHeadRoomMember.size() > 0) {
                    membersHeadAdapter.notifyDataSetChanged();
                }
                mAdapter.notifyDataSetChanged();
            });
        });
    }

    private class GroupMerbersAdapter extends BaseQuickAdapter<BaseSortModel<RoomMember>, BaseViewHolder> {
        List<BaseSortModel<RoomMember>> mSortContactList;

        public GroupMerbersAdapter(List<BaseSortModel<RoomMember>> data) {
            super(R.layout.row_sort_friend, data);
            this.mSortContactList = data;
        }

        @Override
        protected void convert(BaseViewHolder helper, BaseSortModel<RoomMember> item) {
            int position;
            if (isBanned) {
                position = helper.getAdapterPosition();
            } else {
                // 添加了头部 ，所以减1
                position = helper.getAdapterPosition() - 1;
            }
            helper.addOnClickListener(R.id.layout_row_sort);
            TextView categoryTitleTv = helper.getView(R.id.catagory_title);
            ImageView avatar_img = helper.getView(R.id.avatar_img);
            TextView nick_name_tv = helper.getView(R.id.nick_name_tv);
            // 根据position获取分类的首字母的Char ascii值
            int section = ListUtil.getSectionmRoomMemberForPosition(mSortRoomMember, position);
            // 如果当前位置等于该分类首字母的Char的位置 ，则认为是第一次出现
            if (position == ListUtil.getSortRoomMembersPositionForSection(mSortRoomMember, section)) {
                categoryTitleTv.setVisibility(View.VISIBLE);
                categoryTitleTv.setText(mSortContactList.get(position).getFirstLetter());
            } else {
                categoryTitleTv.setVisibility(View.GONE);
            }
            final RoomMember member = mSortContactList.get(position).getBean();
            AvatarHelper.getInstance().displayAvatar(member.getUserId(), avatar_img, true);

            if (coreManager.getSelf().getUserId().equals(member.getUserId())) {
                nick_name_tv.setText(coreManager.getSelf().getNickName());
            } else {
                Friend friend = FriendDao.getInstance().getFriend(CoreManager.getSelf(mContext).getUserId(), member.getUserId());
                if (friend != null && !TextUtils.isEmpty(friend.getRemarkName())) {
                    nick_name_tv.setText(friend.getRemarkName());
                } else if (!TextUtils.isEmpty(member.getShowName())) {
                    nick_name_tv.setText(member.getShowName());
                } else {
                    nick_name_tv.setText(friend.getNickName());
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        if (v == layout_search) {//搜索
            new SearchUtils(GroupMembersListActivity.this, rt_title,
                    ll_main, "请输入昵称或备注名", sortedList, new onItemClickOListener() {
                @Override
                public void onSearchItemClick(RoomMember roomMember) {
                    if (roomMember.getRole() == 1 || roomMember.getRole() == 2) {
                        for (int i = 0; i < mSortHeadRoomMember.size(); i++) {
                            if (mSortHeadRoomMember.get(i).getBean().getUserId() == roomMember.getUserId()) {
                                onItemClick(roomMember, i);
                                return;
                            }
                        }
                    } else {
                        for (int i = 0; i < mSortRoomMember.size(); i++) {
                            if (mSortRoomMember.get(i).getBean().getUserId() == roomMember.getUserId()) {
                                onItemClick(roomMember, i);
                                return;
                            }
                        }
                    }
                }
            }).showSearchBar();
        }
    }


    public void onItemClick(RoomMember roomMember, int position) {
        if (isDelete) {// 踢人
            if (mSortRoomMember.size() + mSortHeadRoomMember.size() < 4) {
                ToastUtil.showToast(mContext, "当前群聊为最少人数，不能删除成员");
                return;
            }
            if (roomMember.getUserId().equals(coreManager.getSelf().getUserId())) {
                ToastUtil.showToast(mContext, R.string.can_not_remove_self);
                return;
            }
            if (roomMember.getRole() == 1) {
                ToastUtil.showToast(mContext, getString(R.string.tip_cannot_remove_owner));
                return;
            }

            if (roomMember.getRole() == 2 && mRoomMember != null && mRoomMember.getRole() != 1) {
                ToastUtil.showToast(mContext, getString(R.string.tip_cannot_remove_manager));
                return;
            }
            DeleteMemberDialog mSF = new DeleteMemberDialog(GroupMembersListActivity.this);
            mSF.setSomething(null, getString(R.string.sure_remove_member_for_group, roomMember.getShowName()),
                    new DeleteMemberDialog.OnSelectionFrameClickListener() {
                        @Override
                        public void cancelClick() {

                        }

                        @Override
                        public void confirmClick(int applyAgain) {
                            deleteMember(roomMember, roomMember.getUserId(), applyAgain, position);
                        }
                    });
            mSF.show();
        } else if (isBanned) {// 禁言
            if (roomMember.getUserId().equals(coreManager.getSelf().getUserId())) {
                ToastUtil.showToast(mContext, R.string.can_not_banned_self);
                return;
            }

            if (roomMember.getRole() == 1) {
                ToastUtil.showToast(mContext, getString(R.string.tip_cannot_ban_owner));
                return;
            }

            if (roomMember.getRole() == 2) {
                ToastUtil.showToast(mContext, getString(R.string.tip_cannot_ban_manager));
                return;
            }

            showBannedDialog(roomMember.getUserId());
        } else if (isSetRemark) {// 备注
           /* if (roomMember.getUserId().equals(coreManager.getSelf().getUserId())) {
                ToastUtil.showToast(mContext, R.string.can_not_remark_self);
                return;
            }*/
            mRoomMember = roomMember;
            setRemarkName(roomMember, roomMember.getUserId(), roomMember.getUserName(), roomMember.getShowName());
        } else {
            Intent intent = new Intent(mContext, PersonalCenterActivity.class);
            intent.putExtra(AppConstant.EXTRA_USER_ID, roomMember.getUserId());
            intent.putExtra(PersonalCenterActivity.KEY_FROM_ADD_TYPE, PersonalCenterActivity.FROM_ADD_TYPE_GROUP);
            mContext.startActivity(intent);
        }
    }

    /**
     * 删除群成员
     */
    private void deleteMember(final RoomMember baseSortModel, final String userId, int applyAgain, int position) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("roomId", mRoomId);
        params.put("userId", userId);
        params.put("applyAgain", String.valueOf(applyAgain));

        DialogHelper.showDefaulteMessageProgressDialog(this);


        HttpUtils.get().url(coreManager.getConfig().ROOM_MEMBER_DELETE)
                .params(params)
                .build()
                .execute(new BaseCallback<Void>(Void.class) {

                    @Override
                    public void onResponse(ObjectResult<Void> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == 1) {
                            Toast.makeText(mContext, R.string.remove_success, Toast.LENGTH_SHORT).show();
                            if (baseSortModel.getRole() == 1 || baseSortModel.getRole() == 2) {
                                mSortHeadRoomMember.remove(position);
                                membersHeadAdapter.notifyDataSetChanged();
                            } else {
                                mSortRoomMember.remove(position);
                                mAdapter.notifyDataSetChanged();
                            }
                            RoomMemberDao.getInstance().deleteRoomMember(mRoomId, userId);
                            EventBus.getDefault().post(new EventGroupStatus(10001, Integer.valueOf(userId)));
                            EventBus.getDefault().post(new EventGroupStatus(111111, 0));//通知群列表刷新

                        } else {
                            Toast.makeText(mContext, R.string.remove_failed, Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showErrorNet(mContext);
                    }
                });
    }

    /**
     * 禁言
     */
    private void bannedVoice(String userId, final long time) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("roomId", mRoomId);
        params.put("userId", userId);
        params.put("talkTime", String.valueOf(time));
        DialogHelper.showDefaulteMessageProgressDialog(this);

        HttpUtils.get().url(coreManager.getConfig().ROOM_MEMBER_UPDATE)
                .params(params)
                .build()
                .execute(new BaseCallback<Void>(Void.class) {

                    @Override
                    public void onResponse(ObjectResult<Void> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode() == 1) {
                            if (time > TimeUtils.sk_time_current_time()) {
                                ToastUtil.showToast(mContext, R.string.banned_succ);
                            } else {
                                ToastUtil.showToast(mContext, R.string.canle_banned_succ);
                            }
                        } else {
                            ToastUtil.showErrorData(mContext);
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showErrorNet(mContext);
                    }
                });
    }

    private void showBannedDialog(final String userId) {
        final int daySeconds = 24 * 60 * 60;
        BannedDialog bannedDialog = new BannedDialog(mContext, new BannedDialog.OnBannedDialogClickListener() {

            @Override
            public void tv1Click() {
                bannedVoice(userId, 0);
            }

            @Override
            public void tv2Click() {
                bannedVoice(userId, TimeUtils.sk_time_current_time() + daySeconds / 48);
            }

            @Override
            public void tv3Click() {
                bannedVoice(userId, TimeUtils.sk_time_current_time() + daySeconds / 24);
            }

            @Override
            public void tv4Click() {
                bannedVoice(userId, TimeUtils.sk_time_current_time() + daySeconds);
            }

            @Override
            public void tv5Click() {
                bannedVoice(userId, TimeUtils.sk_time_current_time() + daySeconds * 3);
            }

            @Override
            public void tv6Click() {
                bannedVoice(userId, TimeUtils.sk_time_current_time() + daySeconds * 7);
            }

            @Override
            public void tv7Click() {
                bannedVoice(userId, TimeUtils.sk_time_current_time() + daySeconds * 15);
            }
        });
        bannedDialog.show();
    }

    /**
     * 对群内成员备注
     */
    private void setRemarkName(RoomMember roomMember, final String userId, String userName, final String name) {
        Intent intent = new Intent(GroupMembersListActivity.this, RoomChangeContentActivity.class);
        intent.putExtra("content", roomMember.getShowName());
        intent.putExtra("change_type", REMARKNAME);
        startActivityForResult(intent, CHANGE_RESULT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CHANGE_RESULT && data != null) {
            String text = data.getStringExtra("content");
            int change_type = data.getIntExtra("change_type", 0);
            if (change_type == REMARKNAME) {//修改群名称返回
                if (TextUtils.isEmpty(text)) {
                    text = mRoomMember.getShowName();
                }
                if (text.equals(mRoomMember.getShowName())) {
                    return;
                }
                Map<String, String> params = new HashMap<>();
                params.put("access_token", coreManager.getSelfStatus().accessToken);
                params.put("roomId", mRoomId);
                params.put("userId", mRoomMember.getUserId());
                params.put("remarkName", text);
                DialogHelper.showDefaulteMessageProgressDialog(GroupMembersListActivity.this);

                String finalNewName = text;
                HttpUtils.get().url(coreManager.getConfig().ROOM_MEMBER_UPDATE)
                        .params(params)
                        .build()
                        .execute(new BaseCallback<Void>(Void.class) {

                            @Override
                            public void onResponse(ObjectResult<Void> result) {
                                DialogHelper.dismissProgressDialog();
                                if (result.getResultCode() == 1) {
                                    ToastUtil.showToast(mContext, R.string.modify_succ);
                                    RoomMemberDao.getInstance().updateRoomMemberCardName(mRoomJid, mRoomMember.getUserId(), finalNewName);

                                    if (mRoomMember.getRole() == 1 || mRoomMember.getRole() == 2) {//判断是否是群主或者群管理
                                        for (int i = 0; i < mSortHeadRoomMember.size(); i++) {
                                            if (mSortHeadRoomMember.get(i).getBean().getUserId().equals(mRoomMember.getUserId())) {
                                                mSortHeadRoomMember.get(i).getBean().setCardName(finalNewName);
                                            }
                                        }
                                        membersHeadAdapter.notifyDataSetChanged();
                                    } else {
                                        for (int i = 0; i < mSortRoomMember.size(); i++) {
                                            if (mSortRoomMember.get(i).getBean().getUserId().equals(mRoomMember.getUserId())) {
                                                mSortRoomMember.get(i).getBean().setCardName(finalNewName);
                                                break;
                                            }
                                        }
                                        mAdapter.notifyDataSetChanged();
                                    }
                                    String loginUserId = coreManager.getSelf().getUserId();
                                    // FriendDao.getInstance().updateRoomName(loginUserId, mRoomJid, finalNewName);
                                    ChatMessageDao.getInstance().updateNickName(loginUserId, mRoomJid, mRoomMember.getUserId(), finalNewName);
                                    // FriendDao.getInstance().updateRoomMyNickName(mRoomJid, finalNewName);
                                    ListenerManager.getInstance().notifyNickNameChanged(mRoomJid, mRoomMember.getUserId(), finalNewName);
                                    // 更新群组信息页面
                                    EventBus.getDefault().post(new EventGroupStatus(10003, 0));
                                } else {
                                    ToastUtil.showToast(mContext, result.getResultMsg());
                                }
                            }

                            @Override
                            public void onError(Call call, Exception e) {
                                DialogHelper.dismissProgressDialog();
                                ToastUtil.showErrorNet(mContext);
                            }
                        });
            }
        }
    }

    //显示索引字母
    private void showTextDialog(String s) {
        mTextDialog.setText(s);
        mTextDialog.setVisibility(View.VISIBLE);
        mHandler.removeMessages(0);
        mHandler.sendEmptyMessageDelayed(0, 100);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    AlphaAnimation aa = new AlphaAnimation(1.0f, 0.0f);//创建一个AlphaAnimation 对象，渐变从1->0
                    aa.setDuration(1000);//设置持续时间
                    aa.setFillAfter(true);
                    mTextDialog.startAnimation(aa);
                    mTextDialog.setVisibility(View.GONE);
                    break;
            }
            super.handleMessage(msg);
        }
    };

}
